import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Select, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {ApplicationRecord} from "@/types/resp/applicationRecord";
import applicationRecordApi from '@/api/applicationRecordApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import ApplicationRecordAdd from "@/pages/applicationRecord/ApplicationRecordAdd.tsx";
import ApplicationRecordView from "@/pages/applicationRecord/ApplicationRecordView.tsx";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import JobDescriptionSelector from "@/pages/jobDescription/JobDescriptionSelector.tsx";
import CandidateSelector from "@/pages/candidate/CandidateSelector.tsx";
import CandidateViewAll from '../candidate/CandidateViewAll';


const ApplicationRecordList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '应聘申请列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<ApplicationRecord[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<ApplicationRecord>> = await applicationRecordApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<ApplicationRecord> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<ApplicationRecord>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName'},
    {title: '招聘岗位名称', dataIndex: 'jobDescriptionName', key: 'jobDescriptionName'},
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '状态', key: 'status', render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '申请';
          else if (record.status === 20) return '面试邀约';
          else if (record.status === 30) return '录用';
          else if (record.status === 90) return '拒绝';
          else return '未知';
        })()}
      </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
          <Button color="primary" variant="outlined" onClick={() => candidateRow(record)}>应聘者详情</Button>
        </Space>
      ),
    },
  ];

  const [applicationRecordAddVisible, setApplicationRecordAddVisible] = useState(false);
  const [applicationRecordViewVisible, setApplicationRecordViewVisible] = useState(false);
  const [candidateViewAllVisible, setCandidateViewAllVisible] = useState(false);
  const [selectedApplicationRecordId, setSelectedApplicationRecordId] = useState(0)
  const [selectedApplicationRecord, setSelectedApplicationRecord] = useState({})

  const onAdd = () => {
    setSelectedApplicationRecordId(0)
    setApplicationRecordAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedApplicationRecordId(id)
    setApplicationRecordAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      applicationRecordApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: ApplicationRecord) => {
    setSelectedApplicationRecord(record)
    setApplicationRecordViewVisible(true)
  };

  const candidateRow = (record: ApplicationRecord) => {
    setSelectedApplicationRecord(record)
    setCandidateViewAllVisible(true)
  };

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [jobDescriptionSelectorVisible, setJobDescriptionSelectorVisible] = useState(false);
  const findJobDescription = () => {
    setJobDescriptionSelectorVisible(true);
  }
  const handleJobDescriptionSelected = (selectedJobDescription: { jobDescriptionId?: number; jobDescriptionName?: string; }) => {
    setJobDescriptionSelectorVisible(false)
    if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      jobDescriptionId: selectedJobDescription['jobDescriptionId'],
      jobDescriptionName: selectedJobDescription['jobDescriptionName'],
      }));
    }
  };
  const handleCloseJobDescriptionSelector = () => {
    setJobDescriptionSelectorVisible(false)
  };
  const [candidateSelectorVisible, setCandidateSelectorVisible] = useState(false);
  const findCandidate = () => {
    setCandidateSelectorVisible(true);
  }
  const handleCandidateSelected = (selectedCandidate: { candidateId?: number; candidateName?: string; }) => {
    setCandidateSelectorVisible(false)
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      candidateId: selectedCandidate['candidateId'],
      candidateName: selectedCandidate['candidateName'],
      }));
    }
  };
  const handleCloseCandidateSelector = () => {
    setCandidateSelectorVisible(false)
  };

  const handleCloseApplicationRecordAdd = () => {
    setApplicationRecordAddVisible(false)
  };

  const handleCloseApplicationRecordView = () => {
    setApplicationRecordViewVisible(false)
  };

  const handleCloseCandidateViewAll = () => {
    setCandidateViewAllVisible(false)
  };

  const [findCandidateFormItem, setFindCandidateFormItem] = useState(false);
  const initByType = () => {
    const type = sessionStorage.getItem('type')
    if (type && Number(type) === 3) {
      form.setFieldsValue({
        candidateId: 2,
        candidateName: '陈静'
      });
      setFindCandidateFormItem(true)
    }
  }

  useEffect(() => {
    initByType()
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="applicationRecordList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="candidateId">
          <Input type="hidden" />
        </Form.Item>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="jobDescriptionName" label="招聘岗位名称">
          <Input.Search placeholder="请选择招聘岗位名称" onSearch={findJobDescription} readOnly={true} />
        </Form.Item>
        <Form.Item name="candidateName" label="应聘者姓名">
          <Input.Search placeholder="请选择应聘者姓名" onSearch={findCandidate} readOnly={true} disabled={findCandidateFormItem}/>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" options={[
            { value: 10, label: <span>申请</span> },
            { value: 20, label: <span>面试邀约</span> },
            { value: 30, label: <span>录用</span> },
            { value: 90, label: <span>拒绝</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
      </Form>
      <Table<ApplicationRecord> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <JobDescriptionSelector visible={jobDescriptionSelectorVisible} onJobDescriptionSelected={handleJobDescriptionSelected} onCloseJobDescriptionSelector={handleCloseJobDescriptionSelector} />
      <CandidateSelector visible={candidateSelectorVisible} onCandidateSelected={handleCandidateSelected} onCloseCandidateSelector={handleCloseCandidateSelector} />
      <ApplicationRecordAdd visible={applicationRecordAddVisible} onCloseApplicationRecordAdd={handleCloseApplicationRecordAdd} id={selectedApplicationRecordId} />
      <ApplicationRecordView visible={applicationRecordViewVisible} onCloseApplicationRecordView={handleCloseApplicationRecordView} viewRow={selectedApplicationRecord} />
      <CandidateViewAll visible={candidateViewAllVisible} onCloseCandidateViewAll={handleCloseCandidateViewAll} viewRow={selectedApplicationRecord} />
    </div>
  );
};

export default ApplicationRecordList;
